<?php
/////////////////////////////////////////////////////////////////////////////
// Framework
//
// Copyright (c) 2009 Yan weidong
//
/////////////////////////////////////////////////////////////////////////////
/**
 * 定义 Action Abstract 类
 *
 * @package mvc
 * @version $Id: abstract.php 256 2008-03-16 19:20:53Z yan weidong $
 */
/**
 * Controller_Abstract 实现了一个其它控制器的超类
 * @package mvc
 */
abstract class actionAbstract 
{

	/**
     * Modules名称
     * @var string
     */
    public $appName;

	/**
     * Controller名称
     * @var string
     */
    public $actionName;

    /**
     * Action名称
     * @var string
     */
    public $functionName;


    /**
     * Action对象
     * @var string
     */
    public $actionObject;

    protected $trace       = array();  // 页面trace变量


    /**
     * 构造函数
     */
    function __construct()
    {
    	global $configs;
        
    	$this->configs = $configs;
		$this->_getUrls();
    }
    

	/**
     * 获取url的值.
     * @return array
     */
    function _getUrls()
    {
    	$pathInfo = empty($_SERVER['PATH_INFO'])?'':$_SERVER['PATH_INFO'];
    	$pathInfo = str_replace(".html","",$pathInfo);
        $urls = explode('/',$pathInfo);
		// get app name.
		if(empty($urls[1])){
			$this->appName = NOT_MODULES;
		} else {
			$this->appName = $urls[1];
		}
		
		// get action name.
		if(empty($urls[2])){
			$this->actionName = DEFAULT_CONTROLLER;
		} else {
			$this->actionName = $urls[2];
		}
		
		// get action name.
		if(empty($urls[3])){
			$this->functionName = 'main';
		} else {
			$this->functionName = $urls[3];
		}
		
		

		//包房商没有酒店跳入链接
		$isbusiness=acl::getCookie('PmsCookie');
        if(!empty($urls[1])&&$urls[1]=="partner"){
            if($urls[2]!="common"&&$urls[3]!="login"){
                if(!isset($_SESSION['hotel_id'])||($isbusiness['isbusiness']==2&&$_SESSION['hotel_id']==0)){
                    setcookie("PmsCookie", "", time() - 3600,'/');
                    unset($_SESSION);
                }else{
                    if($urls[3]!="category"&&$urls[3]!="editcategory"&&$urls[3]!="get_address"&&$_SESSION['hotel_id']==0&&$isbusiness['isbusiness']==1){
        				header("location:/index.php/partner/merchant/category");
        			}
                }
    		}
        }
		
		// get params.
		$keyName = '';
		unset($urls[0],$urls[1],$urls[2],$urls[3]);
		$paramsAry = array_values($urls);
		foreach($paramsAry as $key=>$val){
			if($key %2 == 0){
				$keyName = $val;
				$this->params[$keyName] = '';
			} else {
				$this->params[$keyName] = $val;
			}
		}
    }
	

    /**
     * 执行指定的动作
     * @return mixed
     */
    function execute()
    {
    	
    	$appPath = $this->get_app_path();
    	$this->get_action();
    	
    	if(method_exists($this->actionObject,$this->functionName))
	    	$this->actionObject->{$this->functionName}();
	    elseif(method_exists($this->actionObject,'__go'))
	    	$this->actionObject->__Go();
	    else
	    	Framework::Error('function: <b>__go()</b> or <b>'.$this->functionName.'()</b> not defined on <b>'.$this->actionName .'.php</b>',__FILE__,__LINE__);
			
	    
    }
	
    /**
     * 根据app的参数来获取一个路径.
     *
     * @return string
     */
    function get_app_path()
    {
    	$appPath =  APPS_PATH.$this->appName;
    	if(!is_dir($appPath)) Framework::Error('app: <b>'.$this->appName.'</b> not found ['.$appPath.']',__FILE__,__LINE__);
    	return $appPath;
    }
    
    /**
     * 根据action的参数来获取一个路径.
     *
     * @return string
     */
    function get_action()
    {
    	$actionPath =  APPS_PATH . $this->appName . "/action/".$this->actionName . ".php";
        $notFoundActionPath =  APPS_PATH . $this->appName . "/action/".NOT_CONTROLLER . ".php";

    	if(is_file($actionPath)){
    		include $actionPath;
    		$this->actionObject = new $this->actionName();
    	} elseif(is_file($notFoundActionPath)) {
            include $notFoundActionPath;
            $notFoundActionName = NOT_CONTROLLER;
            $this->actionObject = new $notFoundActionName();
        } else {
    		Framework::Error('action: <b>'.$this->actionName.'</b> not found, for: '.$actionPath,__FILE__,__LINE__);
    	}
    }
    
    
    /**
     * 调入model.
     *
     */
	function loadModel($appsName,$tableName,$primaryKey='id'){
		$modelName = $tableName.'Model';
    	$modelPath =  APPS_PATH . $appsName . "/model/".$modelName . ".php";
    	if(!isset($this->$appsName))
    		$this->$appsName = new stdClass();
    	if(is_file($modelPath)){
    		include_once($modelPath);
    			
    		$this->$appsName->$modelName = new $modelName();
    		
    	} else {
    		$modelPath =  LIBRARY_PATH . "db/model.php";
    		include_once($modelPath);
    		
    		$this->$appsName->$modelName = new model();
    		$this->$appsName->$modelName->_tableName  = $appsName.'_'.$tableName;
    		$this->$appsName->$modelName->_primaryKey = $primaryKey;
    		$this->$appsName->$modelName->_database   = 'portal';
    		
    	}
    	
    	// connection db server.
    	$this->$appsName->$modelName->initDb();
    }
    /**
     * 调入helper.
     *
     */
    function loadHelper($helperFileName){
    	$viewPath =  LIBRARY_PATH . "/helper/".$helperFileName . ".php";
    	 
    	if(!is_file($viewPath)){
    		Framework::Error("helper: <b>$viewPath</b> not found",__FILE__,__LINE__);
    	}
    	 
    	include_once $viewPath;
    }
    
    /**
     * 调入view.
     *
     */
    function loadView($viewFileName=''){
    	if(empty($viewFileName)){
    		$viewPath =  APPS_PATH . $this->appName . "/view/".$this->actionName .  "/".$this->functionName  .".php";
    	} else {
    		$viewPath =  APPS_PATH . $this->appName . "/view/".$viewFileName . ".php";
    	}
    	
    	if(!is_file($viewPath)){
    		Framework::Error("view: <b>$viewPath</b> not found",__FILE__,__LINE__);
    	}
    	
    	return $viewPath;
    }
    
    /*
     * ajax 调入
     */
    function loadAjaxView($viewFileName = '',$data='') {
    	if(empty($viewFileName)){
    		$viewPath =  APPS_PATH . $this->appName . "/view/".$this->actionName .  "/".$this->functionName  .".php";
    	} else {
    		$viewPath =  APPS_PATH . $this->appName . "/view/".$viewFileName . ".php";
    	}
    	
    	if(!is_file($viewPath)){
    		Framework::Error("view: <b>$viewPath</b> not found",__FILE__,__LINE__);
    	}
    	if(!empty($data)) {
    		extract($data);
    	}
    	ob_start();
    	include($viewPath);
    	$result = ob_get_contents();
    	ob_end_clean();
    	return $result;
    }
    
    /**
     * 调入widget.
     *
     */
    function loadWidget($widgetFileName=''){
    	$widgetPath =  ROOT_PATH . "/widget/".$widgetFileName . ".php";
    	 
    	if(!is_file($widgetPath)){
    		Framework::Error("widget: <b>$widgetPath</b> not found",__FILE__,__LINE__);
    	}
    	 
    	return $widgetPath;
    }
    
    /**
     * 调入api
     */
    function loadApi($apiFileName=""){
        $apiPath = APPS_PATH . "api/action/".$apiFileName . ".php";
        
        if(!is_file($apiPath)){
    		Framework::Error("api: <b>$apiPath</b> not found",__FILE__,__LINE__);
    	}
   	    //echo $apiPath;
    	include_once $apiPath;
    }
    
    /**
    *
    *菜单配置载入
    */
    protected function loadConfig($fileName=''){
        if(!$fileName){
            $files = CONFIG_PATH .$this->appName.'.php';
        }else{
            $files = CONFIG_PATH.$fileName.'.php';
        }
         
        if(file_exists($files)){
            return include_once $files;
        }
        return array();
    }
    
    // URL重定向
    protected function redirect($url,  $msg='',$time=0) {
        //多行URL地址支持
        $url = str_replace(array("\n", "\r"), '', $url);
        if (empty($msg))
            $msg = "系统将在{$time}秒之后自动跳转到{$url}！";
        if (!headers_sent()) {
            // redirect
            if (0 === $time) {
                header('Location: ' . $url);
            } else {
                header("refresh:{$time};url={$url}");
                echo($msg);
            }
            exit();
        } else {
            $str = "<meta http-equiv='Refresh' content='{$time};URL={$url}'>";
            if ($time != 0)
                $str .= $msg;
            exit($str);
        }
    }
    //url生成
    // $this->url('controllers/action');
    // $this->url('controllers/action',array('id'=>1));
    // $this->url('controllers/action@appname',array('id'=>1));
    public function url($urls,$arg=array()){
        
        if(is_array($urls)){
            $arg = $urls[1];
            (string)$urls = $urls[0];
        }
        if($urls[0] == '/') return $urls;

        $url = '/index.php/';
        //处理index.php
        if(strpos($_SERVER["REQUEST_URI"],'index.php')){
            $url = '/index.php/';
        }
        if (!strpos($urls, '/')) {
            $urls =$this->actionName.'/'.$urls;
        }

        if (strpos($urls,'@')) {
            $arr=explode('@', $urls);
            $url.=$arr[1].'/'.$arr[0];
        }else{
            $url .= $this->appName.'/'. $urls;
        }
        if(!empty($arg)){
            $str = '';
            foreach ($arg as $k => $v) {
                $str .='&'.$k.'='.$v; 
            }

            if (strpos($urls,'?')) {
                $url .='&'.ltrim($str,'&');
            } else {
                $url .='?'.ltrim($str,'&');
            }

        }
        return $url;
    }

    public function trace($title,$value='') {
        if(is_array($title))
            $this->trace   =  array_merge($this->trace,$title);
        else
            $this->trace[$title] = $value;
    }
    //输出调试信息
    function debug(){
         // 系统默认显示信息
        $this->trace('请求方法',    $_SERVER['REQUEST_METHOD']);
        $this->trace('通信协议',    $_SERVER['SERVER_PROTOCOL']);
        $this->trace('请求时间',    date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']));
        $this->trace('用户代理',    $_SERVER['HTTP_USER_AGENT']);
        $this->trace('会话ID'   ,   session_id());
        $Sql    =  isset($_ENV['Sql'])?$_ENV['Sql']:array();
        $this->trace('SQL记录',count($Sql)?count($Sql).'条<br/>'.implode('<br/>',$Sql):'无SQL记录');
        $files =  get_included_files();
        $this->trace('加载文件',    count($files).str_replace("\n",'<br/>',substr(substr(print_r($files,true),7),0,-2)));
        // 调用Trace页面模板
        include LIBRARY_PATH.'/helper/trace.tpl';
    }
    //魔术方法 有不存在的操作的时候执行
    public function __call($method,$args) {
        switch(strtolower($method)) {
            // 判断提交方式
            case 'ispost':
            case 'isget':
            case 'ishead':
            case 'isdelete':
            case 'isput':
                return strtolower($_SERVER['REQUEST_METHOD']) == strtolower(substr($method,2));
            default:
                return  false;
        }
    }
	
    /**
     * 字符串截取 支持汉英混合  3字节==一个汉字
     */
    function string_substr($str, $len = 12, $dot = true) {
        $i = 0;
        $l = 0;
        $c = 0;
        $a = array();
        while ($l < $len) {
            $t = substr($str, $i, 1);
            if (ord($t) >= 224) {
                $c = 3;
                $t = substr($str, $i, $c);
                $l += 2;
            } elseif (ord($t) >= 192) {
                $c = 2;
                $t = substr($str, $i, $c);
                $l += 2;
            } else {
                $c = 1;
                $l++;
            }
            // $t = substr($str, $i, $c);
            $i += $c;
            if ($l > $len) break;
            $a[] = $t;
        }
        $re = implode('', $a);
        if (substr($str, $i, 1) !== false) {
            array_pop($a);
            ($c == 1) and array_pop($a);
            $re = implode('', $a);
            $dot and $re .= '...';
        }
        return $re;
    }
    
    //权限管理
    function my_authority($method=null){
        //echo "<pre>";print_r($_SESSION['result']);exit;
        if(isset($_SESSION['superMan'])&&$_SESSION['superMan']>0&&!in_array($method, $_SESSION['result'])){
            return false;
        }else{
        	return true;
        }
    }
    
    
    //导出操作
    function outExcel($title,$filed,$res){
        set_time_limit(0);
        // init char
		$res = array_values($res);
		//print_r($res[0]);exit;
		$alphabets = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
	    
		//引入导出phpexcel
		include($_SERVER['DOCUMENT_ROOT'] . "/public/PHPExcel/Classes/PHPExcel.php");
		include($_SERVER['DOCUMENT_ROOT'] . "/public/PHPExcel/Classes/PHPExcel/IOFactory.php");
	    
		// Create new PHPExcel object
		$objPHPExcel = new PHPExcel();
	    
		// Set properties
		$objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
		->setLastModifiedBy("Maarten Balliauw")
		->setTitle("Office 2007 XLSX Test Document")
		->setSubject("Office 2007 XLSX Test Document")
		->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
		->setKeywords("office 2007 openxml php")
		->setCategory($title);
	    
		// Add some data
		$objPHPExcel->setActiveSheetIndex(0);
	    
		foreach($filed as $key=>$val){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($alphabets[$key].'1', $val);
		}
		foreach ($res as $key => $item) {
			$item = array_values($item);
			$objPHPExcel->setActiveSheetIndex(0);
			for($i=0;$i<count($item);$i++){
				$objPHPExcel->setActiveSheetIndex(0)->setCellValue($alphabets[$i].($key + 2), $item[$i]);
			}
		}
		
		$objPHPExcel->getActiveSheet()->setTitle($title);
	    
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);
	    //echo "<pre>";print_r($objPHPExcel);exit;
		header('Content-Type: application/vnd.ms-excel');
		header("Content-Disposition: attachment;filename=$title.xls");
		header('Cache-Control: max-age=0');
	    
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		//$objWriter =$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel); 
		
		$objWriter->save('php://output');
    }
    
    //日志记录
    function setLogs($logs){
        $fleName=$_SERVER['DOCUMENT_ROOT']."/data/Logs/".date('Y-m-d',time()).".txt";
        $th_time=fopen($fleName,"a");
        fwrite($th_time,date('Y-m-d H:i:s',time())."\r\n".$logs."\r\n\r\n\r\n");
        fclose($th_time);
    }
    
	//数据分页	@$sql_from from语句(必须)		@$sql_where 条件语句(必须)		@$sql_order_by 排序语句(必须)
	//@$field_reto 计数搜索的总数(必须)		@$field_re 需要展示的字段(必须)			@$table 表名头(必须)
	//@$uinfo 表名尾(必须)		@$size 每页显示的数目(可选)		@$page 第几页(可选)
	function getPage($sql_from="",$sql_where="",$sql_order_by="",$field_reto="",$field_re="",$table,$uinfo,$page=1,$size=10){
        $this->loadHelper('pager');
		$this->loadModel($table,$uinfo);
		$uinfo=$uinfo."Model";
		$sql_select="select";
		
		//echo $sql_select.$field_reto." as thcount".$sql_from.$sql_where.$sql_order_by;
        $offset = ($page - 1) * $size;
		$reto=$this->$table->$uinfo->fetchRow($sql_select.$field_reto." as thcount".$sql_from.$sql_where.$sql_order_by);
		
		$count=$reto['thcount'];
        $number = ceil( $count / $size );
        $extend = new pager();
        $pageHtml = $extend->outputadmin( $number, $page, "", "", $count, $size );
		
		$re=$this->$table->$uinfo->fetchAll($sql_select.$field_re.$sql_from.$sql_where.$sql_order_by." limit $offset,$size");
		
		return array('re'=>$re,'number'=>$number,'pageHtml'=>$pageHtml,'size'=>$size);
	}
	
}